//
//  NewsDetailViewController.swift
//  知乎日报Demo
//
//  Created by Ann on 2017/10/19.
//  Copyright © 2017年 Ann. All rights reserved.
//

import UIKit

let barHeight:CGFloat = 44.0
let bgHeight:CGFloat = 350.0
let titleFontSize:CGFloat = 24.0
let webViewInset:CGFloat = 250.0
let downLoadPoint:CGFloat = -(bgHeight - 30)

protocol NewsDetialViewDelegate:NSObjectProtocol{
    
    func loadAntherDateNews(date: ChoiceDate)
  
}
//Step.5 创建DetialView
class NewsDetailViewController: UIViewController {
    
    
   fileprivate  var newsId:Int
   fileprivate  var isCanLoadLast:Bool = false
   fileprivate  var isCanLoadNext:Bool = false
   fileprivate  var extraInfo:NewsExtra?
                var theLastPage:Bool?
    var detialViewDelegate:NewsDetialViewDelegate?
    //5.1 透明View
 fileprivate   lazy var tempView:UIView = {
        let temp = UIView()
        temp.backgroundColor = UIColor.clear
    //在ScrollView中偏上
        temp.frame = CGRect(x: 0, y: -bgHeight, width: ScreenWidth, height: bgHeight)
        return temp
    }()
    //5.2 图片 TODO?
  fileprivate  lazy var mainImageView:UIImageView = {
        let image = UIImageView()
        image.image = UIImage(named: "Image_Preview")
    //在WebView内层
        image.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: bgHeight)
        return image
    }()
    //5.3 刷新图片
  fileprivate  lazy var topRefreshImage:UIImageView = {
        
        let img = UIImageView()
        
        img.frame = CGRect(origin: CGPoint(x: ScreenWidth/2-60,y:50),size: CGSize(width: 15,height: 20))
        img.image = UIImage(named: "ZHAnswerViewBackIcon")
        return img
    }()
 
    //5.4 提示文本
  fileprivate  lazy var refreshLabelOne:UILabel = {
        let label = UILabel()
        label.text = "下拉载入上一篇"
        
        label.font = UIFont.systemFont(ofSize: 11)
        label.textColor = UIColor.white
        return label
        
    }()
    //5.3.1 刷新图片
    fileprivate  lazy var bottomRefreshImage:UIImageView = {
        
        let img = UIImageView()
        
        img.frame = CGRect(origin: CGPoint(x: ScreenWidth/2-60,y:50),size: CGSize(width: 15,height: 20))
        img.image = UIImage(named: "ZHAnswerViewBackIcon")
        return img
    }()
    
    //5.4.1 提示文本
    fileprivate  lazy var bottomRefreshLabel:UILabel = {
        let label = UILabel()
        label.text = "上拉载入下一篇"
        
        label.font = UIFont.systemFont(ofSize: 11)
        label.textColor = UIColor.gray
        return label
        
    }()
    
    
    //5.5 图片来源
  fileprivate  lazy var imageSourceLabel:UILabel = {
        let source = UILabel()
        source.font = UIFont.systemFont(ofSize: 6)
        source.textColor = UIColor.white
    source.text = "图片:"
        return source
    }()
    //5.6 新闻标题
   fileprivate lazy var newsTitleLable:UILabel = {
        
        let title = UILabel()
        title.font = UIFont.boldSystemFont(ofSize: titleFontSize)
        title.textColor = UIColor.white
        title.numberOfLines = 0
        title.textAlignment = NSTextAlignment.left
        title.sizeToFit()
        title.text = ""
        return title
    }()
    
    //5.7 下行蒙版背景
   fileprivate lazy var maskBG_botton:UIImageView = {
        let mask = UIImageView()
        mask.image = UIImage(named: "Home_Image_Mask")
        return mask
    }()
    //5.8 上行蒙版背景
   fileprivate lazy var maskBG_top:UIImageView = {
        let mask = UIImageView()
        mask.image = UIImage(named: "News_Image_Mask")
        return mask
    }()
    //5.9 webView
   fileprivate lazy var webView:UIWebView = {
        let web = UIWebView()
    web.backgroundColor = UIColor.white
        web.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight - barHeight)
        return web
    }()
    
    
    
    lazy var statusBarView:StatusBarView = {
        let bar = StatusBarView()
        bar.backgroundColor = UIColor.white
        
        return bar
    }()

    //MARK: - 赞，动画控制板面
    
    var isAnimating:Bool = false
    
    lazy var popularityAnimateView:PopularityView = {
        let v = PopularityView()
        v.backgroundColor =  UIColor(red: 0.098, green: 0.565, blue: 0.827, alpha: 1)
        v.layer.cornerRadius = 3.0
        v.layer.masksToBounds = true;
        return v
    }()
    init(newId:Int) {
        self.newsId = newId
           
        super.init(nibName: nil, bundle: nil)
       
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.white
        //5.11 发起网络请求
        NewsDetialViewModel.loadNewsDetail(newsId: newsId) { (isSuccess, NewsDetial) in
            guard NewsDetial != nil else {
                return
            }
            
            self.loadDetailView(news: NewsDetial!)
            self.bottomRefreshImage.frame = CGRect(x: ScreenWidth/2-60, y: self.webView.scrollView.contentSize.height, width: 15, height: 20)
        }
        
setScrollFromScreen()
setupUI()
loadExtraInfo()
        
       
    }
 
    override func viewDidAppear(_ animated: Bool) {
        //MARK:- 检查导航控制器是否超过2
        if self.navigationController!.viewControllers.count > 2 {
            
            self.navigationController!.viewControllers.remove(at: 1)
        }
        
           }
    
    private func setScrollFromScreen(){
     
        let _sysTarget = self.navigationController?.interactivePopGestureRecognizer?.delegate
       let _newGesture = UIPanGestureRecognizer.init(target: _sysTarget, action:Selector("handleNavigationTransition:"))
        self.view.addGestureRecognizer(_newGesture)
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        _newGesture.delegate = self as? UIGestureRecognizerDelegate
    }
   private func loadDetailView(news:NewsDetial) {
        
        if  var body = news.body {
            if let css = news.css {
                var temp = ""
                for c in css {
                    temp = "<link href='\(c)' rel='stylesheet' type='text/css' />\(temp)"
                }
                
                body = "\(temp) <style> .headline .img-place-holder { height: \(0)px;}</style> \(body)"
                
            }
            
            webView.loadHTMLString(body, baseURL: nil)
        }
        
        
        if  let _image = news.image {
            
            self.mainImageView.kf.setImage(with: URL(string: _image)!, placeholder: UIImage(named: "Image_Preview"))
     
            
           self.webView.scrollView.contentInset = UIEdgeInsetsMake(webViewInset, 0, 0, 0)
            
 
 
            self.imageSourceLabel.text = " 图片 : \(news.image_source ?? "")"
            self.newsTitleLable.text = news.title
          
        }
    
        //这里观察
       
        
        
    }
    
    //MARK:- 加载额外信息
    
  fileprivate  func loadExtraInfo(){
        
        NewsDetialViewModel.loadNewsExtraInfo(id: newsId) { (isTrue, extra) in
            if isTrue {
                self.extraInfo = extra
                self.statusBarView.popCount = extra!.popularity
                self.statusBarView.extraInfo = extra
                self.popularityAnimateView.setCount = extra!.popularity
            }
        }
    }
    
   private func setupUI(){
        
        
         self.view.addSubview(statusBarView)
      statusBarView.statusBarDelegate = self as? StatusBarActionDelegate
        
        popularityAnimateView.alpha = 0
        
        self.view.addSubview(webView)
        
        ///设置web代理
        webView.scrollView.delegate = self as? UIScrollViewDelegate
        webView.scrollView.addSubview(tempView)
        
        webView.scrollView.addSubview(imageSourceLabel)
        webView.scrollView.addSubview(newsTitleLable)
        
    
        
        tempView.addSubview(maskBG_botton)
        tempView.addSubview(maskBG_top)
        
        tempView.addSubview(topRefreshImage)
        tempView.addSubview(self.refreshLabelOne)
        
        
        webView.insertSubview(mainImageView, at: 0)
        webView.delegate = self as? UIWebViewDelegate    //页面加载完成后设置刷新图片的位置
    
        
        
        
         webView.scrollView.addSubview(bottomRefreshImage)
         webView.scrollView.addSubview(bottomRefreshLabel)
         self.view.addSubview(popularityAnimateView)
         layoutView()
         bottomRefreshImage.sizeToFit()
        
        
        
    }
   private func layoutView(){
        statusBarView.snp.makeConstraints { (make) in
            make.bottom.equalTo(view.snp.bottom)
            make.left.equalTo(view.snp.left)
            make.right.equalTo(view.snp.right)
            make.height.equalTo(barHeight)
        }
        imageSourceLabel.snp.makeConstraints { (make) in
            make.right.equalTo(tempView.snp.right).offset(-5)
            
            make.bottom.equalTo(tempView.snp.bottom).offset(-5)
        }
        newsTitleLable.snp.makeConstraints { (make) in
            make.left.equalTo(tempView.snp.left)
            make.right.equalTo(tempView.snp.right)
            make.bottom.equalTo(tempView.snp.bottom).offset(-10-imageSourceLabel.frame.maxY)
        }
        
        maskBG_botton.snp.makeConstraints { (make) in
            make.left.equalTo(tempView.snp.left)
            make.right.equalTo(tempView.snp.right)
            make.top.equalTo(tempView.snp.centerY).offset(20)
            make.bottom.equalTo(tempView.snp.bottom)
        }
        maskBG_top.snp.makeConstraints { (make) in
            make.left.equalTo(tempView.snp.left)
            make.right.equalTo(tempView.snp.right)
            make.bottom.equalTo(tempView.snp.centerY).offset(-25)
            
            make.top.equalTo(tempView.snp.top)//.offset(-25)
        }
        popularityAnimateView.snp.makeConstraints { (make) in
            make.bottom.equalTo(statusBarView.snp.top)
            make.centerX.equalTo(statusBarView.support.snp.centerX)
            make.height.equalTo(20)
            make.width.equalTo(80)
        }
        refreshLabelOne.snp.makeConstraints { (make) in
            make.left.equalTo(topRefreshImage.snp.right).offset(8)
            make.centerY.equalTo(topRefreshImage.snp.centerY)
            
        }
        
 
        
    }
    
    
}
extension NewsDetailViewController:UIScrollViewDelegate{

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //限制下拉滑动
        if scrollView.contentOffset.y <  -bgHeight  {
        scrollView.contentOffset = CGPoint(x: 0, y: -bgHeight)
        }
        //载入上一篇判断
        if scrollView.contentOffset.y < downLoadPoint && !isCanLoadLast{
        rotateAnimateDirection(obj: topRefreshImage, isRefresh: true)
            refreshLabelOne.text = "松开加载"
            isCanLoadLast = true
        }else if scrollView.contentOffset.y > downLoadPoint && isCanLoadLast{
        rotateAnimateDirection(obj: topRefreshImage, isRefresh: false)
             refreshLabelOne.text = "下拉载入上一篇"
            isCanLoadLast = false
        }
        
        //载入下一篇判断
        if scrollView.contentOffset.y + ScreenHeight-barHeight > scrollView.contentSize.height + 100 && !isCanLoadNext {
               rotateAnimateDirection(obj: bottomRefreshImage, isRefresh: true)
              bottomRefreshLabel.text = "松开加载"
            isCanLoadNext = true
         
        
        }else if  scrollView.contentOffset.y + ScreenHeight-barHeight < scrollView.contentSize.height + 100 && isCanLoadNext{
              rotateAnimateDirection(obj: bottomRefreshImage, isRefresh: false)
             bottomRefreshLabel.text = "上拉载入下一篇"
            isCanLoadNext = false
        }
//        print("iscanlast:\(isCanLoadLast)")
//        print("content--Offset:\(scrollView.contentOffset)")
//        print("content--Inset:\(scrollView.contentInset)")
//        print("content--Size:\(scrollView.contentSize)")
//        print("zhen--Offset\(scrollView.contentOffset.y + ScreenHeight-barHeight)")
        
        if scrollView.contentOffset.y >= -webViewInset {
            
              mainImageView.frame = CGRect(x: 0, y: -(scrollView.contentOffset.y + webViewInset) , width: ScreenWidth, height: bgHeight)
         
        }
       
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if isCanLoadLast {
        //上拉刷新
 
            self.detialViewDelegate?.loadAntherDateNews(date: ChoiceDate.lastDate)
        }
        
        if isCanLoadNext{
        //下拉
 
                self.detialViewDelegate?.loadAntherDateNews(date: ChoiceDate.nextData)
        }
    }
    
    

}
extension NewsDetailViewController:UIWebViewDelegate,UIGestureRecognizerDelegate{

    
 func webViewDidFinishLoad(_ webView: UIWebView) {
      
                    bottomRefreshImage.frame = CGRect(x: ScreenWidth/2-60, y: webView.scrollView.contentSize.height+50, width: 20, height: 20)
                bottomRefreshLabel.snp.makeConstraints { (make) in
                make.left.equalTo(bottomRefreshImage.snp.right).offset(8)
                make.centerY.equalTo(bottomRefreshImage.snp.centerY)

                }
    }
    
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if self.navigationController?.viewControllers.count == 1{
            return false
        }
        return true
    }
}
extension NewsDetailViewController:StatusBarActionDelegate{
  fileprivate  func rotateAnimateDirection(obj:UIView,isRefresh:Bool){
        
        if isRefresh {
            
            UIView.animate(withDuration: TimeInterval(0.3), animations: {
                 obj.transform = CGAffineTransform(rotationAngle:CGFloat(.pi - 0.0000001))
            })
            
        }else{
            UIView.animate(withDuration: TimeInterval(0.3), animations: {
                 obj.transform = CGAffineTransform(rotationAngle: CGFloat(2 * .pi + 0.0000001))
            })
            
        }
    }
    func popularityViewAnimate (){
      //  print("AAA")
        //标记动画进行时
        if isAnimating {
            return
        }
        
        statusBarView.isPopularitySelected = statusBarView.isPopularitySelected ? false:true
        
        if statusBarView.isPopularitySelected, let value = statusBarView.popCount  {
            statusBarView.popCount = value + 1
            popularityAnimateView.setCount = statusBarView.popCount!//动画开启后加1
            
        }
        if !statusBarView.isPopularitySelected, let value = statusBarView.popCount{
            statusBarView.popCount = value - 1
            popularityAnimateView.setCount = statusBarView.popCount!
        }
        //acceptAnimateView.setCount =   self.extraInfo!.popularity
        self.isAnimating = true
        
        
        ///如果是取消赞则不进行动画
        if statusBarView.isPopularitySelected == false{
            self.isAnimating = false
            return
            
        }
        
        
        //点赞开始
        UIView.animate(withDuration: TimeInterval(0.2), animations: {
            //isAnimating =
            self.popularityAnimateView.alpha = 1
            var rect = self.popularityAnimateView.frame
            let updateY = rect.origin.y - 28
            rect.origin.y = updateY
            self.popularityAnimateView.frame = rect
            // self.acceptAnimateView.
            
        }) { (finished) in
            
            
            if finished {
                //动态加一
                //   self.acceptAnimateView.setCount =   self.extraInfo!.popularity + 1
                
                UIView.animate(withDuration: TimeInterval(0.2), delay: TimeInterval(0.5), options: [], animations: {
                    
                    self.popularityAnimateView.alpha = 0
                    var rect = self.popularityAnimateView.frame
                    let updateY = rect.origin.y + 22
                    rect.origin.y = updateY
                    self.popularityAnimateView.frame = rect
                }, completion: { (isSucess) in
                    //点赞完成
                    self.isAnimating = false
                    
                })
                
                
                
                
            }
        }
        
        
    }
    func backListViewAction() {
        
       self.navigationController?.popToRootViewController(animated: true)
    }
    func nextPageNewsAction(){
      self.detialViewDelegate?.loadAntherDateNews(date: ChoiceDate.nextData)
    
    }
}
